import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { format } from 'date-fns';
import { CommonService } from '../../../services-common/common.service';
import { divideSharingStatusArrs, divideInstallStatusArrs } from '../status.pipe';
import { GameManageService } from '../game-manage/game-manage.service';
import { PromotionShareService } from '../promotion-share.service';

@Component({
  selector: 'app-divide-game-edit',
  templateUrl: './divide-game-edit.component.html',
  styleUrls: ['./divide-game-edit.component.scss']
})
export class DivideGameEditComponent implements OnInit {

  routeParams: any = {};
  flexLabelWidth = '120px';
  sharingOptions: Array<any> = [...divideSharingStatusArrs];
  installOptions: Array<any> = [...divideInstallStatusArrs];

  channelOptions: Array<any> = [
    { label: '爱思PC端', value: 1 },
    { label: '爱思移动端', value: 2 }
  ];
  channelSelected: Array<any> = []; // 推广渠道
  developerOptons: Array<any> = []; // 开发者列表
  classifyOptions: Array<any> = []; // 应用分类Options

  classifySelected: Array<any> = []; // 应用分类已选项

  warrantDates: any = []; // 授权时间

  validateForm!: FormGroup;
  subLoading = false;

  constructor(
    private msg: NzMessageService,
    private fb: FormBuilder,
    private activatedRoute: ActivatedRoute,
    private commonService: CommonService,
    private services: GameManageService,
    private promotionShareService: PromotionShareService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      developerId: ['', [Validators.required]], // 开发者
      name: ['', [Validators.required]], // 名称
      icon: ['', [Validators.required]], // 图标
      cornerMarker: [''], // 角标
      subtitle: [''], // 广告语
      remark: [''], // 描述
      coverPhoto: [''], // 游戏引导图
      backUrl: [''], // 支付回调地址

      copyright: [''], // 著作权证书
      isbn: [''], // 游戏版号
      authorization: [''], // 授权书
      
      sharingMode: ['', [Validators.required]], // 分成方式
      commission: ['', [Validators.required]], // 可赚多少
      earnedBase: [''], // 已赚基数 - 人
      totalAmount: [''], // 已赚基数 - 金额
      
      userType: ['', [Validators.required]], // 用户类型
      promotionChannels: ['', [Validators.required]], // 推广渠道
      installMode: [''], // 安装方式
      gameUrl: [''], // 链接
      state: ['', [Validators.required]], // 状态 0：启用 1：禁用
      typeId: [''], // 分类
      isRecommend: ['', [Validators.required]] // 新游推荐
    });

    this.loadDeveloperTable();
    this.loadClassifyOptionsData();

    if (this.routeParams.id) {
      this.loadDetailsData();
    }
  }

  // 查询分类Options
  async loadClassifyOptionsData() {
    let params = {
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.promotionShareService.getGameTypeList(params);

    if (code === 0) {
      this.classifyOptions = data || [];
    }
  }

  // 开发者list
  async loadDeveloperTable() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const {code, data, message}: any = await this.promotionShareService.getDeveloperList(params);

    if (code === 0) {
      this.developerOptons = data.records || [];
    } else {
      this.msg.error(message);
    }
  }

  async loadDetailsData() {
    let params = {
      id: this.routeParams.id
    }
    const msgId = this.msg.loading('数据加载中..', { nzDuration: 0 }).messageId;;
    const {code, data, message}: any = await this.promotionShareService.getAppDetailsData(params);
    this.msg.remove(msgId);

    if (code === 0) {
      this.validateForm.patchValue({
        developerId: !this.commonService.isEmpty(data.developerId) ? data.developerId : '', // 开发者
        name: data.name || '', // 名称
        icon: data.icon || '', // 图标
        cornerMarker: data.cornerMarker || '', // 角标
        subtitle: data.subtitle || '', // 广告语
        remark: data.remark || '', // 描述
        coverPhoto: data.coverPhoto || '', // 游戏引导图
        backUrl: data.backUrl || '', // 支付回调地址

        copyright: data.copyright || '', // 著作权证书
        isbn: data.isbn || '', // 游戏版号
        authorization: data.authorization || '', // 授权书
        
        sharingMode: !this.commonService.isEmpty(data.sharingMode) ? data.sharingMode : '', // 分成方式
        commission: data.commission || '', // 可赚多少
        earnedBase: data.earnedBase || '', // 已赚基数 - 人
        totalAmount: !this.commonService.isEmpty(data.totalAmount) ? data.totalAmount : '', // 已赚基数 - 金额
        
        userType: !this.commonService.isEmpty(data.userType) ? data.userType : '', // 用户类型
        promotionChannels: !this.commonService.isEmpty(data.promotionChannels) ? data.promotionChannels : '', // 推广渠道
        installMode: !this.commonService.isEmpty(data.installMode) ? data.installMode : '', // 安装方式
        gameUrl: data.gameUrl || '', // 链接
        state: !this.commonService.isEmpty(data.state) ? data.state : '', // 状态 0：启用 1：禁用
        typeId: !this.commonService.isEmpty(data.typeId) ? data.typeId : '', // 分类
        isRecommend: !this.commonService.isEmpty(data.isRecommend) ? data.isRecommend : '' // 新游推荐 0：启用 1：禁用
      });

      this.channelSelected = data.promotionChannels === 0 ? [1, 2] : [data.promotionChannels]; // 推广渠道
      this.classifySelected = !this.commonService.isEmpty(data.typeId) ? data.typeId.split(',').map((m: any) => +m) : []; // 分类options

      // 授权时间
      if (data.authDate) {
        let dateArrs = data.authDate.split(',');
        this.warrantDates = [new Date(dateArrs[0]), new Date(dateArrs[1])];
      } else {
        this.warrantDates = [];
      }
    } else {
      this.msg.error(message);
    }
  }

  async submitFormData() {
    if (this.validateForm.valid) {
      let params: any = {
        ...this.validateForm.value,
        authDate: this.warrantDates.length ? `${format(this.warrantDates[0], 'yyyy-MM-dd')},${format(this.warrantDates[1], 'yyyy-MM-dd')}` : '' // 授权时间
      }
      let res: any = null;

      this.subLoading = true;
      if (this.routeParams.id) {
        params.id = this.routeParams.id,
        res = await this.services.updateGameInfo(params);
      } else {
        res = await this.services.addGameItemData(params);
      }
      this.subLoading = false;
      
      if (res.code === 0) {
        this.msg.success('操作成功');
        this.pageBack();
      } else {
        this.msg.error(res.message);
      }
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  channelChange() {
    if (this.channelSelected.length) {
      this.validateForm.patchValue({
        promotionChannels: this.channelSelected.length > 1 ? 0 : this.channelSelected[0]
      });

      ['installMode', 'gameUrl'].forEach(key => {
        if (this.channelSelected.includes(1)) {
          this.validateForm.get(key)!.setValidators(Validators.required);
          this.validateForm.get(key)!.markAsDirty();
        } else {
          this.validateForm.get(key)!.clearValidators();
          this.validateForm.get(key)!.markAsPristine();

          this.validateForm.patchValue({
            installMode: '',
            gameUrl: ''
          })
        }
        this.validateForm.get(key)!.updateValueAndValidity();
      })
    }
  }

  // 分类选择Change
  classifyChange(ev: any) {
    this.validateForm.get('typeId')?.setValue(ev.join(','));
  }

  pageBack() {
    history.back();
  }
}
